<template>
	<el-drawer size="480px" :title="title" :visible.sync="visible">
		<el-form ref="form" v-loading="loading" :model="formData" :rules="formRules" class="dict_enum_table">
			<el-table :data="formData.enums">
				<el-table-column label="名称" min-width="210">
					<el-form-item slot-scope="{ row, $index }" :prop="`enums.${$index}.deName`" :rules="formRules.deName">
						<el-input v-model="row.deName" placeholder="请输入内容" :disabled="row.readonly"></el-input>
					</el-form-item>
				</el-table-column>
				<el-table-column label="值" min-width="100">
					<el-form-item slot-scope="{ row, $index }" :prop="`enums.${$index}.deValue`" :rules="formRules.deValue">
						<sw-custom-input input-type="number" v-model="row.deValue" :disabled="row.readonly" />
					</el-form-item>
				</el-table-column>
				<el-table-column label="排序" width="64" align="center">
					<el-form-item slot-scope="{ row, $index }" :prop="`enums.${$index}.sort`" :rules="formRules.sort">
						<sw-custom-input class="number" input-type="number" v-model="row.sort" :disabled="row.readonly" />
					</el-form-item>
				</el-table-column>
				<el-table-column label="操作" :width="handleWidth" v-if="isHasAuthButton">
					<template slot-scope="{ row, $index }">
						<template v-if="!row.readonly">
							<el-button type="text" v-hasPermi="updateButton" @click="handleUpdateEnum(row, $index)">保存</el-button>
						</template>
						<template v-else>
							<el-button type="text" v-hasPermi="updateButton" @click="handleEditEnum(row)">修改</el-button>
						</template>
						<el-button type="text" v-hasPermi="deleteButton" :disabled="!row.readonly && !!row.id" @click="handleDeleteEnum(row, $index)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-form>
		<el-button type="text" class="dict_enum_added" v-hasPermi="addedButton" @click="handleAddedEnum()">添加字典枚举</el-button>
	</el-drawer>
</template>

<script>
import lodash from 'lodash';
import { mapGetters } from 'vuex';
import { addedDictDetail, updateDictDetail } from '@/api/system/tbSysDictDetail';
import { getDictDetailList, deleteDictDetail } from '@/api/system/tbSysDictDetail';
export default {
	props: {
		authBtns: { type: Array, default: () => [] },
		value: { type: Boolean, default: false },
		dataId: { type: String, default: '' },
		title: { type: String, default: '' }
	},
	data() {
		const dictNameValidator = (rule, value, callback) => {
			if (!value) return callback(new Error('请输入字典名称'));
			let duplicates = this.formData.enums.filter((item, index) => {
				return item.deName === value && index !== parseInt(rule.field.split('.')[1]);
			});
			return duplicates.length > 0 ? callback(new Error('已存在字典名称')) : callback();
		};
		return {
			visible: this.value,
			loading: false,
			baseTable: [],
			formData: { enums: [] },
			formRules: {
				deName: [{ validator: dictNameValidator, trigger: 'blur' }],
				deValue: [{ required: true, message: '请输入字典值', trigger: 'blur' }],
				sort: [{ required: true, message: '请输入字典排序', trigger: 'blur' }]
			}
		};
	},
	computed: {
		...mapGetters(['authButton']),
		addedButton() {
			let addedData = lodash.find(this.authBtns, { field: 'enumAdded' });
			return addedData?.id;
		},
		updateButton() {
			let updateData = lodash.find(this.authBtns, { field: 'enumUpdate' });
			return updateData?.id;
		},
		deleteButton() {
			let deleteData = lodash.find(this.authBtns, { field: 'enumDelete' });
			return deleteData?.id;
		},
		intersectionBtns() {
			let btns = lodash.compact([this.updateButton, this.deleteButton]);
			return lodash.intersectionWith(this.authButton, btns, (n, k) => n.id === k);
		},
		isHasAuthButton() {
			return this.intersectionBtns.length > 0;
		},
		handleWidth() {
			let columnWidth = 0;
			this.intersectionBtns.forEach((n, idx) => {
				let btnData = lodash.find(this.authBtns, { id: n.id });
				let labelLen = (btnData?.label?.length || 0) / 2;
				columnWidth += labelLen * 15 + (idx !== 0 ? 12 : 2);
			});
			return columnWidth + 32;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.loading = true;
			this.getDictDetailData();
		}
	},
	methods: {
		//获取字典枚举列表
		async getDictDetailData() {
			let params = { page: 1, limit: 999, dictId: this.dataId };
			let result = await getDictDetailList(params).then((res) => res.data);
			this.loading = false;
			if (result.code === '0') {
				let datas = result.data || [];
				let dataArr = datas.map((n) => ({ ...n, readonly: true }));
				this.baseTable = lodash.cloneDeep(dataArr);
				this.formData['enums'] = [...dataArr];
			}
		},

		//添加字典枚举
		handleAddedEnum() {
			let enums = this.formData.enums;
			let baseLen = this.baseTable.length;
			if (enums.length === baseLen && !lodash.some(enums, { readonly: false })) {
				enums.push({ deName: '', deValue: '', sort: '', readonly: false });
			} else {
				this.$message.warning('请先保存已添加的枚举');
			}
		},

		//修改字典枚举
		handleEditEnum(row) {
			let enums = this.formData.enums || [];
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				enums.forEach((item) => this.$set(item, 'readonly', true));
				this.$set(row, 'readonly', false);
			});
		},

		//保存字典枚举
		handleUpdateEnum(row) {
			this.$refs['form'].validate((valid) => {
				if (!valid) return false;
				if (!row.id) {
					this.addedDictEnumData(row);
				} else {
					this.updateDictEnumData(row);
				}
			});
		},

		//删除字典枚举
		handleDeleteEnum(row, index) {
			if (!row.id) {
				this.$delete(this.formData.enums, index);
			} else {
				this.$confirm('确定删除该字典枚举吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
					beforeClose: async (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							await this.deleteDictEnumData(row.id);
							instance.confirmButtonLoading = false;
						}
						done();
					}
				}).catch(() => {});
			}
		},

		//添加字典枚举数据
		async addedDictEnumData(data) {
			let params = { ...data, dictId: this.dataId };
			let result = await addedDictDetail(params).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('添加字典枚举成功');
				this.getDictDetailData();
			}
		},

		//修改字典枚举数据
		async updateDictEnumData(data) {
			let params = { ...data };
			let result = await updateDictDetail(params).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('修改字典枚举成功');
				this.getDictDetailData();
			}
		},

		//删除字典枚举数据
		async deleteDictEnumData(id) {
			let result = await deleteDictDetail(id).then((res) => res.data);
			if (result.code === '0') {
				this.$message.success('删除字典枚举成功');
				this.getDictDetailData();
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.dict_enum_table {
	flex: 1;
	width: 100%;
	overflow: hidden;
	.el-table {
		height: 100%;
	}
	.el-form-item {
		margin-bottom: 0;
	}
	&:deep(.el-table__header) th {
		background-color: var(--primary-background-plain-disabled);
	}
	&:deep(.el-table__cell) .cell {
		display: block;
		line-height: 1;
		font-size: 15px;
		padding: 6px 16px;
	}
	&:deep(td.el-table__cell) {
		padding: 0;
		.cell {
			padding: 0;
		}
		&:last-child {
			padding: 0 16px;
		}
	}
	&:deep(.el-input__inner) {
		height: auto;
		padding: 16px;
		line-height: 1;
		color: #606266;
		font-size: 15px;
		border-color: transparent;
	}
	&:deep(.el-table__row):hover td {
		background-color: transparent !important;
	}
	.el-input.is-disabled:deep(.el-input__inner) {
		cursor: default;
		background-color: transparent;
	}
	.el-input.number:deep(.el-input__inner) {
		text-align: center;
	}
	.el-button {
		font-size: 15px;
	}
	&:deep(.is-error) .el-input__inner {
		border-color: #f56c6c;
	}
}
.dict_enum_added {
	padding: 16px;
	font-size: 16px;
}
</style>
